package com.example.demo.ai.upload;

import com.example.demo.ai.sftp.SftpConfig;
import com.example.demo.ai.sftp.SftpService;
import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

@Service
public class UploadImageDriService {

    @Autowired
    private SftpService sftpService;
    @Autowired
    private SftpConfig config;

    public String uploadFolder(String localFolderPath) throws JSchException {
        Channel channel = sftpService.createChannel("sftp");
        ChannelSftp sftp = (ChannelSftp) channel;
        if(sftp == null) return null;
        try{
            String remoteDir = config.getRemote();
            remoteDir = remoteDir.replace("\\", "/");
            remoteDir = remoteDir+"/"+System.currentTimeMillis();
            return uploadDirectory(sftp, new File(localFolderPath), remoteDir);
        } catch (Exception e){
            System.out.println("gg");
        } finally {
            sftp.exit();
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        return null;
    }

    private String uploadDirectory(ChannelSftp sftp, File localDir, String remoteDir)
            throws SftpException, IOException {

        String resultDri = createDirectoryIfNotExists(sftp, remoteDir);

        File[] files = localDir.listFiles();
        if (files == null) return null;

        for (File file : files) {
            String remotePath = remoteDir + "/" + file.getName();
            if (file.isDirectory()) {
                uploadDirectory(sftp, file, remotePath);
            } else {
                uploadFile(sftp, file.getAbsolutePath(), remoteDir);
                System.out.println("已上传: " + file);
            }
        }
        return resultDri;
    }

    private String createDirectoryIfNotExists(ChannelSftp sftp, String dirPath) throws SftpException {
        try {
            SftpATTRS attrs = sftp.lstat(dirPath);
            if (attrs.isDir()) {
                return dirPath; // 目录已存在
            }
            throw new SftpException(ChannelSftp.SSH_FX_FAILURE, "路径已存在但不是目录: " + dirPath);
        } catch (SftpException e) {
            if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
                // 递归创建父目录
                int lastSlash = dirPath.lastIndexOf('/');
                if (lastSlash > 0) {
                    String parent = dirPath.substring(0, lastSlash);
                    createDirectoryIfNotExists(sftp, parent);
                }

                // 创建当前目录
                try {
                    sftp.mkdir(dirPath);
                    System.out.println("创建目录成功: " + dirPath);
                } catch (SftpException mkdirEx) {
                    // 处理目录创建冲突
                    if (mkdirEx.id != ChannelSftp.SSH_FX_FAILURE) throw mkdirEx;

                    try {
                        if (sftp.lstat(dirPath).isDir()) {
                            System.out.println("目录已被其他进程创建: " + dirPath);
                            return dirPath;
                        }
                    } catch (SftpException ex) {
                        System.err.println("目录创建失败: " + dirPath);
                        System.err.println("最终错误: " + ex);
                    }
                    throw new SftpException(ChannelSftp.SSH_FX_PERMISSION_DENIED,
                            "目录创建被拒绝，请检查权限: " + dirPath);
                }
            } else {
                throw e;
            }
        }
        return dirPath;
    }

    private void uploadFile(ChannelSftp sftp, String localFile, String remoteDir)
            throws SftpException, IOException {
        File file = new File(localFile);
        String remotePath = remoteDir.replace("\\", "/") + "/" + file.getName();

        try (InputStream is = Files.newInputStream(file.toPath())) {
            sftp.put(is, remotePath);
        } catch (SftpException e) {
            System.err.println("文件上传失败: " + remotePath);
            throw e;
        }
    }
}
